package vn.hust.homebudget.utily;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.HashMap;

import vn.hust.homebudget.BudgetBaseActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;

public class BudgetBaseAction extends Helpers{
	
	private static HashMap<Object, Activity> activityStack = new HashMap<Object, Activity>();
	
	/** remove redundant activity on stack from application */
	public synchronized void removeRedundantActivity(BudgetBaseActivity activity) {	
		if (activityStack.containsKey(activity.getClass())) {
			Activity act = activityStack.get(activity.getClass());
			if (act != activity) {
				activityStack.get(activity.getClass()).finish();
				activityStack.remove(activity.getClass());
				activityStack.put(activity.getClass(), activity);
			}
		} else {
			activityStack.put(activity.getClass(), activity);
		}
	}
	
	/** catch uncaughtException from activities based on this activity */
	public void handleUnCaughtException(final BudgetBaseActivity activity){
		Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
			public void uncaughtException(Thread thread, Throwable throwable) {
				throwable.printStackTrace();
				final Throwable throwableObj = throwable;
				activity.runOnUiThread(new Thread() {
					public void run() {
						ByteArrayOutputStream baos = new ByteArrayOutputStream();
						PrintWriter printWriter = new PrintWriter(baos);
						throwableObj.printStackTrace(printWriter);
						String trace = new String(baos.toByteArray());
						try {baos.close();} catch (Exception ignore) {}
						try {printWriter.close();} catch (Exception ignore) {}
						new AlertDialog.Builder(activity).setMessage("Error " + throwableObj + ": " + trace).setPositiveButton("OK", null).setCancelable(false).show();
					}
				});
			}
		});
	}
	
	/** send broadcast QUIT message to quit the application*/
	public void broadcastQuitMessage(Context context) {
		Intent intent = new Intent("QUIT");
		context.sendBroadcast(intent);
	}
}
